import sqlite3
import os
from datetime import datetime

# 数据库文件路径
DB_PATH = os.path.join(os.path.dirname(__file__), "fault_management.db")

def get_db_connection():
    """获取数据库连接"""
    conn = sqlite3.connect(DB_PATH)
    conn.row_factory = sqlite3.Row  # 使结果可以通过列名访问
    # 设置文本工厂以正确处理UTF-8编码
    conn.text_factory = lambda x: str(x, 'utf-8') if isinstance(x, bytes) else str(x)
    return conn

def init_db():
    """初始化数据库表"""
    conn = get_db_connection()
    cursor = conn.cursor()
    
    # 创建故障统计表（根据设备预警故障台账结构）
    cursor.execute('''
        CREATE TABLE IF NOT EXISTS fault_statistics (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            factory_name TEXT NOT NULL,
            host_name TEXT NOT NULL,
            fault_time DATETIME NOT NULL,
            alarm_name TEXT NOT NULL,
            level TEXT,
            device_sn TEXT,
            resolution TEXT,
            recovery_time datetime,
            note1 TEXT,
            note2 TEXT
        )
    ''')
    
    conn.commit()
    conn.close()

def init_sample_data():
    """初始化示例数据"""
    conn = get_db_connection()
    cursor = conn.cursor()
    
    # 检查是否已有数据
    cursor.execute("SELECT COUNT(*) FROM fault_statistics")
    count = cursor.fetchone()[0]
    
    # 不再插入示例数据，保持数据库为空
    # 直接提交并关闭连接
    conn.commit()
    conn.close()

# 初始化数据库
if __name__ == "__main__":
    init_db()
    init_sample_data()
    print("数据库初始化完成")